import 'dart:async';
import 'dart:convert';
import 'dart:math';

import 'package:aliplayer_widget/aliplayer_widget_lib.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:gameplay_flutter/lib_basemodel/discover/gift_record_dto_entity.dart';
import 'package:gameplay_flutter/lib_basemodel/discover/play_auth_entity.dart';
import 'package:get/get.dart';
import 'package:ones/extension/common.dart';
import 'package:rich_text_controllerx/rich_text_controllerx.dart';

import '../../lib_basemodel/discover/comment_entity.dart';
import '../../lib_basemodel/discover/moment_entity.dart';
import '../../lib_chat/chat/index.dart';
import '../../lib_im/index.dart';
import '../../lib_network/http_api.dart';
import '../../lib_network/http_helper.dart';
import '../../lib_runtime/event_bus.dart';
import '../../lib_runtime/event_constant.dart';
import '../../resource/language/generated/l10n.dart';
import '../post/model/at_user_model.dart';
import '../sel_friend/sel_friend_view.dart';

class PlayerLogic extends GetxController with GetTickerProviderStateMixin, WidgetsBindingObserver {
  var moment = (Get.arguments["moment"] as MomentEntity).obs;
  var keyboardHeight = 0.0.obs;

  // var moment = MomentEntity().obs;

  late var tabController = TabController(length: 2, vsync: this);
  var lockMode = false.obs;

  var playControllerList = <AliPlayerWidgetController>[].obs;
  late AliPlayerWidgetController currentController;
  var pageController = PageController();

  late TabController giftTabController;
  List<ImGitfModel> gifts = [];
  var wrappers = <ImGitfWrapperModel>[].obs;
  ImGitfModel? gift;
  var giftCount = 1.obs;

  var currentPlayAuth = PlayAuthEntity().obs;
  var currentIndex = 0;

  var dramas = <MomentEntity>[].obs;
  var currentDrama = MomentEntity().obs;

  var giftDto = GiftRecordDtoEntity().obs;
  var giftList = <GiftRecordDtoList>[].obs;
  var comments = <CommentEntity>[].obs;

  var previewText = "";
  var messageController = RichTextController(
    text: '',
    onMatch: (match) {
      // print("match.first ${match.first} ${match}");
    },
    targets: [
      MatchTargetItem.regex(
        RegExp(r'(^|\s)@([\S]+([^\s]))', unicode: true),
        style: const TextStyle(color: Color(0xff8A72FE), fontWeight: FontWeight.bold),
      ),
    ],
  );
  var messageFocus = FocusNode();

  var showWhiteInput = false.obs;
  var showEmojiView = false.obs;
  var showSendButton = false.obs;
  var sendEnable = false.obs;

  var atUsers = <FriendModel>[].obs;
  var toSendComment = <ATUserModel>[].obs;

  var hintText = T.current.discover3_say_something.obs;
  var targetComment = CommentEntity().obs;
  int? commentId;

  late StreamSubscription<bool> keyboardSubscription;

  var keyboardVisibilityController = KeyboardVisibilityController();

  @override
  void didChangeMetrics() {
    keyboardHeight(Get.mediaQuery.viewInsets.bottom - (Get.bottomBarHeight / Get.pixelRatio));
    super.didChangeMetrics();
  }

  @override
  void onInit() async {
    WidgetsBinding.instance.addObserver(this);
    // ImAPI.giftList();
    getBalance();
    currentDrama(moment());
    currentController = AliPlayerWidgetController(Get.context!);
    // currentController.;
    playControllerList.add(currentController);
    loadDramas();
    pageController.addListener(_onPageChanged);

    // Subscribe
    keyboardSubscription = keyboardVisibilityController.onChange.listen((bool visible) {
      debugPrint('Keyboard visibility update. Is visible: $visible');
      lockMode(visible || showEmojiView());

      if (!visible && !showEmojiView()) {
        showWhiteInput(false);
        messageFocus.unfocus();
      }
    });

    // messageFocus.addListener(() {
    //   showWhiteInput(messageFocus.hasFocus);
    // });
    messageFocus.addListener(
      () {
        if (messageFocus.hasFocus) {
          showEmojiView(false);
          showSendButton(true);
        } else {
          if (showEmojiView()) {
            showSendButton(true);
            showWhiteInput(true);
          } else {
            showSendButton(false);
            showWhiteInput(false);
          }
        }
      },
    );
    messageController.addListener(
      () {
        if (messageController.text.isNotEmpty) {
          sendEnable(true);
        } else {
          sendEnable(false);
        }
      },
    );
    getGiftData();
    super.onInit();
  }

  @override
  void onClose() {
    messageFocus.unfocus();
    for (var value in playControllerList) {
      value.destroy();
    }
    keyboardSubscription.cancel();
    messageController.dispose();
    messageFocus.dispose();
    pageController.dispose();
    super.onClose();
  }

  getCurrentPlayController(int index) {
    if (playControllerList.length < index + 1) {
      playControllerList.add(AliPlayerWidgetController(Get.context!));
    }
    return playControllerList[index];
  }

  getPlayAuth() async {
    if (currentDrama().files.isEmpty) return;
    // currentPlayAuth(PlayAuthEntity.fromJson(res.result.first));
    // debugPrint("player logic: getPlayAuth: ${currentPlayAuth()}");
    configPlayerData();

    //
    // var videoId = currentDrama().files.first.videoId;
    // // var videoId = "e0bb414806ff71f08e322680f9ea0102";
    //
    // var res = await HttpHelper.instance().post(
    //   HttpApi.getPlayAuth,
    //   body: {"videoId": videoId},
    //   showLoading: true,
    //   showToast: true,
    // );
    // if (res.result is List && (res.result as List).isNotEmpty) {
    //   currentPlayAuth(PlayAuthEntity.fromJson(res.result.first));
    //   debugPrint("player logic: getPlayAuth: ${currentPlayAuth()}");
    //   configPlayerData();
    // }
  }

  configPlayerData() {
    if (currentDrama().files.isEmpty || currentDrama().files.first.videoUrl.isEmpty) {
      print("无video url数据");
      return;
    }
    final data = AliPlayerWidgetData(
      sceneType: SceneType.listPlayer,
      // videoUrl: currentPlayAuth().playURL,
      videoUrl: currentDrama().files.first.videoUrl,
      coverUrl: currentDrama().cover ?? "",
      // videoTitle: "Sample Video Title",
    );
    currentController.setLoop(true);
    currentController.configure(data);
  }

  loadDramas() async {
    var res = await HttpHelper.instance().post(
      HttpApi.flowVideo,
      showLoading: true,
      showToast: true,
    );

    EasyLoading.show();
    Future.delayed(1.seconds, () {
      EasyLoading.dismiss();
    });

    print("loadDramas ${res.result}");
    if (res.result is List) {
      print("loadDramas list: ${res.result.length}");
      (res.result as List).map(
        (e) {
          print("loadDramas list item: ${e}");
        },
      );
    }
    final moments = ((res.result as List).map((e) => MomentEntity.fromJson(e)));
    dramas.clear();
    dramas.add(moment());
    dramas.addAll(moments.where((element) => element.id != moment().id));
    if (dramas.isNotEmpty) {
      currentDrama(dramas.first);
    }
    getPlayAuth();
  }

  void _onPageChanged() {
    // 获取当前页面索引
    final newPageIndex = pageController.page?.round() ?? 0;

    // 如果当前页面索引和新页面索引相同，则不执行任何操作
    if (currentIndex == newPageIndex) {
      return;
    }

    debugPrint("_onPageChanged [index] [$currentIndex->$newPageIndex]");

    dramas[currentIndex] = currentDrama();
    // 更新当前页面索引
    currentIndex = newPageIndex;
    currentController.stop();
    if (currentIndex + 1 > playControllerList.length) {
      playControllerList.add(AliPlayerWidgetController(Get.context!));
    }
    currentDrama(dramas[currentIndex]);
    currentController = playControllerList[currentIndex];
    playVideo();
  }

  playVideo() async {
    getPlayAuth();
  }

  dynamicGifts() async {
    var res = await HttpHelper.instance().post(
      HttpApi.dynamicGifts,
      body: {"pageNum": 1, "pageSize": 1000, "dynamicId": currentDrama().id},
      showLoading: false,
      showToast: true,
    );

    giftDto(GiftRecordDtoEntity.fromJson(res.result));
    giftList.assignAll(giftDto().list);
    print("sdjflkasdjflkj  ${giftList.length}");
  }

  discoverCommentList() async {
    var res = await HttpHelper.instance().post(
      HttpApi.discoverCommentList,
      body: {"dynamicId": currentDrama().id, "pageNum": 1, "pageSize": 100},
      showLoading: false,
      showToast: true,
    );
    comments.assignAll((res.result["list"] as List?)?.map((e) => CommentEntity.fromJson(e)) ?? []);
  }

  discoverComment() async {
    if (messageController.text.isEmpty) return;

    print(json.encode(convertStringToATUserModels(messageController.text, atUsers())));
    var contents = json.encode(convertStringToATUserModels(messageController.text, atUsers()));

    var res = await HttpHelper.instance().post(
      HttpApi.discoverComment,
      body: {
        "dynamicId": currentDrama().id,
        if (commentId != null) "commentId": commentId,
        "contentInfoListStr": contents
      },
      showLoading: true,
      showToast: true,
    );
    messageController.text = "";
    atUsers.clear();
    messageFocus.unfocus();
    showEmojiView(false);
    if (!(Get.isBottomSheetOpen ?? false)) {
      showWhiteInput(false);
    }
    discoverCommentList();
    currentDrama.update(
      (val) {
        val?.comments += 1;
      },
    );
    discoverDynamicFind();
    lockMode(false);
    // comments.assignAll((res.result["list"] as List?)?.map((e) => CommentEntity.fromJson(e)) ?? []);
  }

  like(MomentEntity moment) async {
    var res = await HttpHelper.instance().post(
      HttpApi.discoverLike,
      body: {"dynamicId": moment.id, "status": moment.isLike ? 0 : 1},
      showLoading: false,
      showToast: true,
    );
    if (res.isSuccess) {
      moment?.likes = moment.likes + (moment.isLike ? -1 : 1);
      moment?.isLike = moment.isLike.not();
      eventBus.fire(moment.isLike ? LikeAction(moment) : UnLikeAction(moment));
      currentDrama(moment);
      dramas.refresh();
      showSendButton.refresh();
    }
  }

  likeComment(CommentEntity comment) async {
    var res = await HttpHelper.instance().post(
      HttpApi.discoverLikeComment,
      body: {"commentId": comment.id, "status": comment.isLike == 1 ? 0 : 1},
      showLoading: false,
      showToast: true,
    );
    discoverCommentList();
  }

  attention(MomentEntity moment) async {
    var res = await HttpHelper.instance().post(
      HttpApi.discoverAttention,
      body: {"isAttention": moment.isAttention == 1 ? 0 : 1, "toUserId": moment.userId},
      showLoading: false,
      showToast: true,
    );
    eventBus.fire(FollowUserAction());
    moment.isAttention = moment.isAttention == 1 ? 0 : 1;
    dramas.refresh();
  }

  deleteComment(int id) async {
    var res = await HttpHelper.instance().post(
      HttpApi.discoverDeleteComment,
      body: {"id": id},
      showLoading: true,
      showToast: true,
    );
    discoverCommentList();

    currentDrama.update(
      (val) {
        val?.comments -= 1;
      },
    );
    discoverDynamicFind();
    // comments.assignAll((res.result as List).map((e) => MomentEntity.fromJson(e)));
  }

  clickComment() async {
    // hintText(T.current.discover3_say_something);
    showEmojiView(false);
    commentId = null;
    messageFocus.requestFocus();
  }

  void _openKeyboard() {
    FocusScope.of(Get.context!).requestFocus(messageFocus); // 请求焦点
  }

  getFocus() {
    Future.delayed(200.milliseconds, () {
      messageFocus.requestFocus();
      if (!messageFocus.hasFocus) getFocus();
    });
  }

  atUser() async {
    var user = await Get.to(() => SelFriendPage());
    showWhiteInput(true);
    getFocus();
    // _openKeyboard();
    if (user is FriendModel) {
      atUsers.add(user);
      var mText = messageController.text;
      if (mText.endsWith(' @')) {
        messageController.text = "$mText${user.nickname} ";
      } else {
        messageController.text = "$mText @${user.nickname} ";
      }
    }
  }

  clickGift() async {}

  void getGiftData() async {
    final results = ImAPI.giftLocalList();
    gifts = results.$1;
    wrappers.assignAll(results.$2);
    giftTabController = TabController(length: wrappers.length, vsync: this);
  }

  void setGiftCount(int count) {
    if (count == giftCount.value) return;
    giftCount.value = count;
  }

  List<ImGitfModel> getGifts(ImGitfWrapperModel wrapper) {
    final ids = wrapper.giftVos.map((e) => e.id).toList();
    final matchedGifts = gifts.where((gift) => ids.contains(gift.id)).toList();
    return matchedGifts;
  }

  void showGift(BuildContext context, String obj) async {
    if (balance() <= 0) {
      EasyLoading.showToast(T.current.c_no_balance);
      return;
    }

    var allP = (gift?.price ?? 0) * giftCount();

    if (balance() < allP) {
      EasyLoading.showToast(T.current.c_no_balance);
      return;
    }

    var res = await HttpHelper.instance().post(
      HttpApi.discoverSendGift,
      body: {
        "userIds": currentDrama().userId,
        "productId": gift?.id,
        "amount": giftCount(),
        "timestamp": DateTime.now().millisecondsSinceEpoch,
        "actionType": 6,
        "price": gift?.price,
        "dynamicId": currentDrama().id,
      },
      showLoading: false,
      showToast: true,
    );

    gift = null;

    getBalance();
    if (res.isSuccess) {
      if (Get.isBottomSheetOpen ?? false) Get.back();

      balance(max(0, balance() - (giftCount() * (gift?.price ?? 0)).toInt()));

      var i = dramas.indexWhere((element) => element.id == currentDrama().id);
      var drama = currentDrama()..rewards += giftCount();
      currentDrama(drama);
      if (i >= 0) dramas[i] = currentDrama();
      dramas.refresh();

      discoverDynamicFind();
      if (context.mounted) {
        showDialog(
          context: context,
          barrierColor: Colors.transparent,
          barrierDismissible: false,
          builder: (_) => MessageGiftSvga(
            obj,
            callback: () {
              try {
                if (Navigator.of(context).canPop()) {
                  Navigator.of(context).pop();
                }
              } catch (e) {}
            },
          ),
        );
      }
    }
  }

  discoverDynamicFind() async {
    var res = await HttpHelper.instance().post(
      HttpApi.discoverDynamicFind,
      body: {"dynamicId": currentDrama().id},
      showLoading: false,
      showToast: true,
    );

    var drama = MomentEntity.fromJson(res.result);

    var i = dramas.indexWhere((element) => element.id == currentDrama().id);
    currentDrama(drama);
    if (i >= 0) dramas[i] = currentDrama();

    print("sdjflkasdjflkj count ${currentDrama().rewards}");
  }

  var balance = 0.obs;

  void getBalance() async {
    final value = await ImAPI.getBalance();
    balance(value);
  }
}
